﻿using BZ.Logger;
using BZVision;
using DevComponents.DotNetBar.Keyboard;
using NDK.Module.BLL;
using NDK.Module.DAL;
using NDK.Module.Model;
using NDK.Module.StationLogic;
using NDK.Motion.BLL;
using NDK.Motion.Frm;
using NDK.Motion.MachineManager;
using NDK.Motion.Sys;
using NDK.Utils;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using VisionPlatform;
using static NDK.Module.Model.Common;

namespace NDK.Frm
{

    public partial class Frm_Main : Form
    {
        #region fileds/properties
        private static log4net.ILog visionLogger = log4net.LogManager.GetLogger("VisionLogger");
        #endregion fileds/properties

        #region 解决闪烁问题
        /// <summary>
        /// 解决闪烁问题
        /// </summary>
        //protected override CreateParams CreateParams
        //{
        //    get
        //    {
        //        CreateParams cp = base.CreateParams;
        //        cp.ExStyle |= 0x02000000;
        //        return cp;
        //    }
        //}
        #endregion

        #region 窗体对象实例，单例模式,保证整个工程只有一个实例
        private static Frm_Main _instance;
        private static readonly object singletonLock = new object();
        System.Timers.Timer timer;
        public static Frm_Main Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (singletonLock)
                    {
                        if (_instance == null)
                        {
                            _instance = new Frm_Main();
                        }
                    }
                }
                return _instance;
            }
        }
        #endregion

        private Frm_Main()
        {
            InitializeComponent();
            AppendUiLog = GlobleLoggerConfiguration.Config();

            ProTypeListItemsInit();

            #region 五分钟没有鼠标键盘响应就上锁(指纹锁权限要用的)
            msg = new UserOptionCheckBFMessage();
            Application.AddMessageFilter(msg);
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.WorkerSupportsCancellation = true;
            #endregion

            #region 上传苹果MacMini通信回调函数
            //AsyncClient_MacMini.Completed += new Action<System.Net.Sockets.TcpClient, AsyncTcpIpUtils.EnSocketAction>(CompletedFromMacMini);
            //AsyncClient_MacMini.Received += new Action<string, string>(ReceivedFromMacMini);
            #endregion
        }

        public void ReceivedFromMacMini(string key, string msg)
        {
            string Recv = string.Empty;
            AsyncRcvMsgFromMacMini = "";

            Recv = msg;
            msg = "";

            if (Recv.Split('@')[0].Equals("ok"))
            {

                if (Recv.Split('@')[1].Contains("success"))
                {
                    AsyncRcvMsgFromMacMini = "MacMiniOk";
                }
                else
                {
                    AsyncRcvMsgFromMacMini = "MacMiniOkElse";
                }
            }
            else if (Recv.Split('@')[0].Equals("ng"))
            {
                AsyncRcvMsgFromMacMini = "MacMiniNg";
            }
            else if (Recv.Split('@')[0].Equals("err"))
            {
                if (Recv.Split('@')[1].Contains("please create one with 'start' command first"))
                {
                    AsyncRcvMsgFromMacMini = "MacMiniErrWithoutStart";
                }
                else
                {
                    AsyncRcvMsgFromMacMini = "MacMiniErr";
                }
            }
            else if (Recv.Split('@')[0].Equals("bad"))
            {
                AsyncRcvMsgFromMacMini = "MacMiniBad";
            }

            AppendUiLog.Log("RcvMacMini: " + Recv, LogType.Alert);

            try
            {
                WriteLogToTxt(Recv + "\r\n");
            }
            catch (Exception EX)
            {
                AppendUiLog.Log("接收写入数据出错" + EX.ToString(), LogType.Error);
            }
        }

        public void CompletedFromMacMini(System.Net.Sockets.TcpClient c, AsyncTcpIpUtils.EnSocketAction enAction)
        {
            try
            {
                IPEndPoint iep = c.Client.RemoteEndPoint as IPEndPoint;
                string key = string.Format("{0}:{1}", iep.Address.ToString(), iep.Port);
                switch (enAction)
                {
                    case AsyncTcpIpUtils.EnSocketAction.Connect:
                        break;
                    case AsyncTcpIpUtils.EnSocketAction.SendMsg:
                        break;
                    case AsyncTcpIpUtils.EnSocketAction.Close:
                        MachineStatusManager.CurrentMachineStatus = MachineStatus.Alarm;
                        button1.BackColor = Color.Red;

                        AppendUiLog.Log("与苹果MacMini断开连接，请检查", LogType.Alert);
                        if (DialogResult.OK == MessageBox.Show("监测到上传MacMini断开连接，请确认MacMini是否正常！"))
                        {
                            try
                            {
                                AsyncClient_MacMini.Disconnect();
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("断开MacMini连接异常" + ex.ToString());
                            }

                            MachineStatusManager.CurrentMachineStatus = MachineStatusManager.LastMachineStatus;
                        }
                        else
                        {
                            AsyncClient_MacMini.Disconnect();
                            MachineStatusManager.CurrentMachineStatus = MachineStatusManager.LastMachineStatus;
                        }
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                AppendUiLog.Log(ex.ToString(), LogType.Error);
            }
        }

        private static void WriteLogToTxt(string strLog)
        {

            String System_Now_Time = null;
            String File_Create_Time = null;

            System_Now_Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff");//HH:mm:ss
            File_Create_Time = DateTime.Now.ToString("yyyyMMdd");
            string logDocument = File_Create_Time + ".txt";

            string str = Process.GetCurrentProcess().MainModule.FileName;
            string logFilePath = str.Substring(0, str.LastIndexOf("\\")) + "\\RecvInfoLogMacMini";
            if (!Directory.Exists(logFilePath))
            {
                Directory.CreateDirectory(logFilePath);
            }
            logFilePath = logFilePath + "//" + logDocument;
            FileStream fs = new FileStream(logFilePath, FileMode.Append);
            StreamWriter sw = new StreamWriter(fs, Encoding.Default);
            sw.WriteLine(System_Now_Time + ":   " + strLog);
            sw.Flush();
            sw.Close();
            fs.Close();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            #region UI
            //修改主窗体的样式
            StyleUtils.MainFormStyle(this);
            //修改子窗体的样式
            StyleUtils.SetMdiStyle(this, Frm_Home.Instance, 0, tlp_Menu.Height);
            StyleUtils.SetMdiStyle(this, Frm_Setting.Instance, 0, tlp_Menu.Height);
            StyleUtils.SetMdiStyle(this, Frm_Login.Instance, 0, tlp_Menu.Height);
            StyleUtils.SetMdiStyle(this, Frm_Statistics.Instance, 0, tlp_Menu.Height);
            StyleUtils.SetMdiStyle(this, Frm_Alarm2.Instance, 0, tlp_Menu.Height);
            StyleUtils.SetMdiStyle(this, Frm_YieldStatistics.Instance, 0, tlp_Menu.Height);


            tlp_FrmContainer.Controls.Add(Frm_Home.Instance, 0, 2);
            tlp_FrmContainer.Controls.Add(Frm_Setting.Instance, 0, 2);
            tlp_FrmContainer.Controls.Add(Frm_Login.Instance, 0, 2);
            tlp_FrmContainer.Controls.Add(Frm_Statistics.Instance, 0, 2);
            tlp_FrmContainer.Controls.Add(Frm_Alarm2.Instance, 0, 2);
            tlp_FrmContainer.Controls.Add(Frm_YieldStatistics.Instance, 0, 2);


            Frm_Home.Instance.Dock = DockStyle.Fill;
            Frm_Setting.Instance.Dock = DockStyle.Fill;
            Frm_Login.Instance.Dock = DockStyle.Fill;
            Frm_Statistics.Instance.Dock = DockStyle.Fill;
            Frm_Alarm2.Instance.Dock = DockStyle.Fill;
            Frm_YieldStatistics.Instance.Dock = DockStyle.Fill;

            if (CurProType == "Block_Min")
            {
                Common.whichBlock = 0;
            }
            else if (CurProType == "Block_Mid")
            {
                Common.whichBlock = 1;
            }
            else if (CurProType == "Block_Max")
            {
                Common.whichBlock = 2;
            }
            else
            {
                Common.whichBlock = -1;
            }
            Frm_Home.Instance.Show();
            #endregion
            if (!isLoadOffLine)
                VisionManager.Event.GetAuthority += Event_GetAuthority;
            ucBtnExt_MachineInfo.BtnText = ProjectName;
            this.WindowState = FormWindowState.Maximized;

            UpdateMeasureItemsEnable += UpdateProTypeMeasureItemsEnable;


            #region 连接苹果MacMini服务器
            bool bConnectSelfOK = true;
            try
            {
                if (Line == "右" && !屏蔽Apple上传)
                {
                    bConnectSelfOK = AsyncClient_MacMini.ConnectAsync("169.254.1.10", 1111);

                    if (!bConnectSelfOK)
                    {
                        button1.BackColor = Color.Red;
                        AppendUiLog.Log("连接MacMini失败！", LogType.Error);
                    }
                    else
                    {
                        if (屏蔽Apple上传 == true)
                        {
                            button1.BackColor = Color.PaleGreen;
                        }
                        else
                        {
                            button1.BackColor = Color.Yellow;
                        }
                        AppendUiLog.Log("连接MacMini成功！", LogType.Alert);
                    }
                }
                else
                {
                    button1.BackColor = Color.Yellow;
                    AppendUiLog.Log("未打开MacMini连接！", LogType.Alert);
                }
            }
            catch (Exception ex)
            {
                button1.BackColor = Color.Red;
                AppendUiLog.Log("连接MacMini异常！" + ex.ToString(), LogType.Error);
            }
            #endregion

            if (b硬件初始化成功 == true && bConnectSelfOK == true)//Common.isFingerPrintInitialed
            {
                AppendUiLog.Log("设备初始化成功，请复位", LogType.Info);
                MachineStatusManager.CurrentMachineStatus = MachineStatus.Initialized;
            }
            else
            {
                AppendUiLog.Log("设备初始化失败，请检查", LogType.Error);
                MachineStatusManager.CurrentMachineStatus = MachineStatus.Unknown;
            }

            ScreenMode.Text = "投屏1";

            PublicMethod.IniBackgroundWorker();
            timer = new System.Timers.Timer();
            timer.Enabled = true;
            timer.Elapsed += Timer_Elapsed; timer.Start();
        }

        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                if (!PublicMethod.worker_TriColorLamp.IsBusy)
                    PublicMethod.worker_TriColorLamp.RunWorkerAsync();
                if (!PublicMethod.worker_AxisStatus.IsBusy)
                    PublicMethod.worker_AxisStatus.RunWorkerAsync();
                if (!PublicMethod.worker_Home.IsBusy)
                    PublicMethod.worker_Home.RunWorkerAsync();
                if (!PublicMethod.worker_ScanButton.IsBusy)
                    PublicMethod.worker_ScanButton.RunWorkerAsync();
                if (!PublicMethod.worker_MonitorEMGSignal.IsBusy)
                    PublicMethod.worker_MonitorEMGSignal.RunWorkerAsync();
                if (!PublicMethod.worker_MonitorDoorGSignal.IsBusy)
                    PublicMethod.worker_MonitorDoorGSignal.RunWorkerAsync();
                if (!PublicMethod.worker_UserOptionCheckBFMessage.IsBusy)
                    PublicMethod.worker_UserOptionCheckBFMessage.RunWorkerAsync();
                if (!PublicMethod.worker_PointCheck.IsBusy)
                    PublicMethod.worker_PointCheck.RunWorkerAsync();
                if (!PublicMethod.worker_SendPCHeartbeatToPLC.IsBusy)
                    PublicMethod.worker_SendPCHeartbeatToPLC.RunWorkerAsync();
                if (!PublicMethod.worker_SaveImage.IsBusy)
                    PublicMethod.worker_SaveImage.RunWorkerAsync();
                if (!PublicMethod.worker_SaveImage1.IsBusy)
                    PublicMethod.worker_SaveImage1.RunWorkerAsync();
                if (!PublicMethod.worker_PCAlarmStatusToPLC.IsBusy)
                    PublicMethod.worker_PCAlarmStatusToPLC.RunWorkerAsync();
                if (!PublicMethod.worker_DoorButtonStatus.IsBusy)
                    PublicMethod.worker_DoorButtonStatus.RunWorkerAsync();
            }
            catch (Exception ex)
            {

            }
        }

        public Authority Event_GetAuthority()
        {
            switch (Common.Authority)
            {
                case "Operator":
                case "BZ":
                case "EN":
                case "Battery QM":
                //return Authority.ProdocutOp;
                case "Apple":
                    return VisionPlatform.Authority.ProdouctEng;
                default:
                    return VisionPlatform.Authority.ProdouctEng;//暂时有算法权限
            }
        }

        #region 快捷键
        string LogKey = "000";

        /// <summary>
        /// 按ESC退出程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_ESCKeyPress(object sender, KeyEventArgs e)
        {
            if (e.Shift && e.Control && e.KeyCode == Keys.B)//调用Block点检
            {
                if (isBlockPointCheck)
                {
                    isBlockPointCheck = false;
                    AppendUiLog.Log("气缸信号RunB00000");
                }
                else
                {
                    isBlockPointCheck = true;
                    AppendUiLog.Log("气缸信号RunB11111");
                }
            }
            if (e.Shift && e.Control && e.KeyCode == Keys.G)//调用GRR点检
            {
                if (isProductPointCheck)
                {
                    isProductPointCheck = false;
                    AppendUiLog.Log("气缸信号RunG00000");
                }
                else
                {
                    isProductPointCheck = true;
                    AppendUiLog.Log("气缸信号RunG11111");
                }
            }
        }
        #endregion 按ESC键，退出程序

        #region 主界面按钮点击事件
        private void ucBtnImg_Home_BtnClick(object sender, EventArgs e)
        {
            chb1.Visible = true;
            //HOperatorSet.ReadImage(out HObject Image, "F:\\图片\\2024-08-05\\Product_麻面\\1\\OK\\GJ7H6VWF1C70000V46+FUS424CF0623_613\\上CCD2.bmp");
            //DateTime dt1 = DateTime.Now;
            //HSmartWindowControl hSmartWindow = new HSmartWindowControl();
            //HOperatorSet.GetImageSize(Image,out HTuple width,out HTuple height);
            //HOperatorSet.SetWindowExtents(hSmartWindow.HalconWindow, 0,0,width-1,height-1);
            //HOperatorSet.SetPart(hSmartWindow.HalconWindow, 0, 0, height - 1, width - 1);
            //HOperatorSet.DispImage(Image, hSmartWindow.HalconWindow);
            //HOperatorSet.DumpWindowImage(out HObject a1, hSmartWindow.HalconWindow);
            //MessageBox.Show((DateTime.Now - dt1).TotalMilliseconds.ToString());
            ////MessageBox.Show((DateTime.Now-dt1).TotalMilliseconds.ToString());
            ////HOperatorSet.DumpWindow( hSmartWindow.HalconWindow,0,"D:\\1111111111111111.jpg");
            //HOperatorSet.WriteImage(a1,"jpg",0, "D:\\1111111111111111.jpg");


            Frm_Setting.Instance.Hide();
            Frm_Login.Instance.Hide();
            Frm_Home.Instance.Show();
            Frm_Statistics.Instance.Hide();
            Frm_Alarm2.Instance.Hide();
            Frm_YieldStatistics.Instance.Hide();
        }

        private void ucBtnImg_Setting_BtnClick(object sender, EventArgs e)
        {
            if (username == "Apple" || username == "superadmin"
                  || username == "EN"
                  || username == "Battery QM")
            {
                Frm_Home.Instance.Hide();
                Frm_Login.Instance.Hide();
                Frm_Setting.Instance.Show();
                Frm_Statistics.Instance.Hide();
                Frm_Alarm2.Instance.Hide();
                Frm_YieldStatistics.Instance.Hide();
            }
            else
            {
                MessageBox.Show(this, "无权限!", "Tip", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (username == "Battery QM")
            {
                //Frm_Setting.Instance.sti_TrackSetting.Visible = true;
                //Frm_Setting.Instance.superTabItem2.Visible = true;
                //Frm_Setting.Instance.superTabItem4.Visible = true;
                //Frm_Setting.Instance.superTabItem1.Visible = true;
                //Frm_Setting.Instance.tab_SizeConfig.Visible = true;
                //Frm_Setting.Instance.superTabItem8.Visible = true;
                //Frm_Setting.Instance.dgv_Home.Enabled = false;
                //Frm_Setting.Instance.dgv_SizeConfig.Enabled = false;
            }
            else if (username == "EN" || username == "Apple" || username == "superadmin")
            {
                //Frm_Setting.Instance.sti_TrackSetting.Visible = true;
                //Frm_Setting.Instance.superTabItem2.Visible = true;
                //Frm_Setting.Instance.superTabItem4.Visible = true;
                //Frm_Setting.Instance.superTabItem1.Visible = true;
                //Frm_Setting.Instance.tab_SizeConfig.Visible = true;
                //Frm_Setting.Instance.superTabItem8.Visible = true;
                //Frm_Setting.Instance.dgv_Home.Enabled = true;
                //Frm_Setting.Instance.dgv_SizeConfig.Enabled = true;
            }
        }

        private void ucBtnImg_Vision_BtnClick(object sender, EventArgs e)
        {
            if (username == "EN" || username == "Apple" || username == "superadmin")
            {
                if (!Frm_VisionDebug.Instance.Visible)
                {
                    Frm_VisionDebug.Instance.Show(this);
                }
            }
            else
            {
                MessageBox.Show(this, "无权限!", "Tip", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void ucBtnImg_Statistics_BtnClick(object sender, EventArgs e)
        {
            Frm_Setting.Instance.Hide();
            Frm_Login.Instance.Hide();
            Frm_Home.Instance.Hide();
            Frm_Statistics.Instance.Hide();
            Frm_Alarm2.Instance.Hide();
            Frm_YieldStatistics.Instance.Show();

            //Frm_Setting.Instance.Hide();
            //Frm_Login.Instance.Hide();
            //Frm_Home.Instance.Hide();
            //Frm_Statistics.Instance.Show();
            //isHomeFormShow = false;
            //isSettingFormShow = false;
            //isStatisticsFromShow = true;
            //isVisionFromshow = false;
            //isLoginFormshow = false;
            //isAlarmFromshow = false;
        }

        private void ucBtnImg_Alarm_BtnClick(object sender, EventArgs e)
        {
            Frm_Alarm2.Instance.dtp_StartDate.Text = DateTime.Now.AddDays(-1).ToString();
            Frm_Alarm2.Instance.dtp_EndDate.Text = DateTime.Now.ToString();
            Frm_Alarm2.Instance.dtp_StartTime.Text = DateTime.Now.ToString();
            Frm_Alarm2.Instance.dtp_EndTime.Text = DateTime.Now.ToString();

            Frm_Home.Instance.Hide();
            Frm_Login.Instance.Hide();
            Frm_Setting.Instance.Hide();
            Frm_Statistics.Instance.Hide();
            Frm_Alarm2.Instance.Show();
            Frm_YieldStatistics.Instance.Hide();

            isHomeFormShow = false;
            isSettingFormShow = false;
            isStatisticsFromShow = false;
            isVisionFromshow = false;
            isLoginFormshow = false;
            isAlarmFromshow = true;
        }

        private void ucBtnImg_Start_BtnClick(object sender, EventArgs e)
        {
            PublicMethod.Start();
        }

        private void ucBtnImg_Pause_BtnClick(object sender, EventArgs e)
        {
            PublicMethod.Pause();
        }
        private void ucBtnImg_Homing_BtnClick(object sender, EventArgs e)
        {
            PublicMethod.Intial();
        }
        private void ucBtnImg_Stop_BtnClick(object sender, EventArgs e)
        {
            PublicMethod.Stop();
        }

        private void ucBtnImg_OpenFile_BtnClick(object sender, EventArgs e)
        {
            if (FileUtils.IsExistDirectory(dataSavePath))
            {
                Process.Start(dataSavePath);
            }
            else
            {
                FileUtils.CreateDirectory(dataSavePath);
                Process.Start(dataSavePath);
            }
        }

        private void ucBtnImg_OpenPicture_BtnClick(object sender, EventArgs e)
        {
            if (FileUtils.IsExistDirectory(picSavePath))
            {
                Process.Start(picSavePath);
            }
            else
            {
                FileUtils.CreateDirectory(picSavePath);
                Process.Start(picSavePath);
            }
        }

        private void ucBtnImg_Login_BtnClick(object sender, EventArgs e)
        {
            Frm_Setting.Instance.Hide();
            Frm_Login.Instance.Show();
            Frm_Home.Instance.Hide();
            Frm_Statistics.Instance.Hide();
            Frm_YieldStatistics.Instance.Hide();
        }

        private void ucBtnExt_MachineInfo_BtnClick(object sender, EventArgs e)
        {
            Dlg_Version.Instance.ShowDialog(this);
        }

        private void btn_PointCheckReview_BtnClick(object sender, EventArgs e)
        {
            Dlg_PointCheck pointCheckDlg = new Dlg_PointCheck();
            pointCheckDlg.Show();
        }
        #endregion

        #region 锁屏
        private void btn_LockScreen_Click(object sender, EventArgs e)
        {
            Frm_LockScreen.Instance.ShowDialog(this);
        }
        #endregion 锁屏

        #region 软键盘
        private void btn_TouchKeyBoard_Click(object sender, EventArgs e)
        {
            this.touchKeyboard1.ShowKeyboard(this, TouchKeyboardStyle.Inline);
        }
        #endregion

        #region 指纹锁
        public void RegiserLockProcess()
        {
            if (backgroundWorker1.IsBusy)
                return;
            backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            while (msg.RegiserLockFlag)
            {
                msg.nUserOptionsCount++;
                if (msg.nUserOptionsCount > 5)
                {
                    //五分钟不动鼠标键盘时的执行操作函数。
                    msg.nUserOptionsCount = 0;

                    Common.Authority = "OP";
                    fingerPrintAuthority = "";

                    Frm_Login.Instance.SetPassCode();

                    string halconExamples = FileUtils.GetAppDirectory();

                    isFileSetPassCode = true;
                    ProcedurePath = halconExamples + @"\hdevengine\procedures.{2559a1f2-21d7-11d4-bdaf-00c04f60b9f0}";

                    break;
                }

                Thread.Sleep(60000);
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            Frm_Setting.Instance.Hide();
            Frm_Login.Instance.Hide();
            Frm_Home.Instance.Show();
            Frm_Statistics.Instance.Hide();
            Frm_YieldStatistics.Instance.Hide();

            isHomeFormShow = true;
            isSettingFormShow = false;
            isStatisticsFromShow = false;
            isVisionFromshow = false;
            isLoginFormshow = false;

            RegiserLockProcess();
        }

        #endregion

        #region 事件
        private void Frm_Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            MachineStatusManager.CurrentMachineStatus = MachineStatus.Quit;
            foreach (var item in Machine.DicCamera.Keys)
            {
                Machine.DicCamera[item].CloseCamera();
            }
            foreach (var item in Machine.DicLaser.Keys)
            {
                Machine.DicLaser[item].DisConnect();
            }
            if (Line=="左")
            {
                try
                {
                    foreach (var item in Machine.DicInputIODoorButton.Keys)
                    {
                        string strNum = item.Substring(6);
                        string strOpenDoor = "门" + strNum + "关门锁定";
                        Machine.DicOutputIO[strOpenDoor].OFF();
                    }
                }
                catch (Exception)
                {

                }
             
            }
          
            PublicMethod.StopMachine();
            Process.GetCurrentProcess().Kill();
            Application.Exit();
        }
        #endregion

        #region UI

        private void ucBtnImg_MouseEffected(object sender, EventArgs e)
        {
            var btn = sender as HZH_Controls.Controls.UCBtnExt;
            btn.FillColor = Color.FromArgb(238, 238, 237);
        }

        private void ucBtnImg_MouseEffecting(object sender, EventArgs e)
        {
            var btn = sender as HZH_Controls.Controls.UCBtnExt;
            btn.FillColor = Color.FromArgb(174, 218, 151);
        }


        #endregion

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            Frm_InitItemStatu.Instance.Show(this);
        }

        private void Frm_Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            Dlg_InputMsgComfirm inputMsgComfirmDlg = new Dlg_InputMsgComfirm(Configuration.language == Configuration.Language.Chinese ? "确认框" : "Confirm Dialog", Configuration.language == Configuration.Language.Chinese ? "确认关闭软件？" : "Close the Software Now?");
            if (inputMsgComfirmDlg.ShowDialog(this) == DialogResult.Cancel)
            {
                e.Cancel = true;
            }
            else
            {
                DateTime startTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                DateTime endTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").ToString());
                int timeCount = (endTime - startTime).Seconds;
                AlarmInfo alarmInfo = new AlarmInfo()
                {
                    StartTime = startTime,
                    EndTime = endTime,
                    TimeCount = timeCount,
                    Type = "软件关闭",
                    Description = "手动关闭软件，关闭原因：" + inputMsgComfirmDlg.msg
                };

                AlarmInfoServices AlarmInfoServices = new AlarmInfoServices();
                AlarmInfoServices.Add(alarmInfo);
            }
        }

        private void settingToolStripMenuItem_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (username == "Apple" || username == "superadmin"
                  || username == "EN"
                  || username == "Battery QM")
            {
                if (e.ClickedItem == tsmi_MotionConfig)//运动参数配置
                {
                    Frm_MachineConfig.Instance.Show();
                }
            }
            else
            {
                MessageBox.Show(this, "无权限!", "Tip", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
        }

        private void tsmi_OpenProject_Click(object sender, EventArgs e)
        {
            if (username == "Apple" || username == "superadmin"
                      || username == "EN"
                      || username == "Battery QM")
            {
                if (MachineStatusManager.CurrentMachineStatus == MachineStatus.Homing
                    || MachineStatusManager.CurrentMachineStatus == MachineStatus.Running
                    )
                {
                    MessageBox.Show("设备正在运行，请先停止！");
                }
                OpenFileDialog mDialog = new OpenFileDialog();
                mDialog.Filter = "(*.json)|*.json";
                if (DialogResult.OK == mDialog.ShowDialog())
                {

                    ProjectName = mDialog.SafeFileName.Split('.')[0];
                    MachineDataManager.ProjectName = ProjectName;
                    ucBtnExt_MachineInfo.BtnText = ProjectName;
                    MachineDataManager.Instance.Init();
                    MachineDataManager.LoadFromFile();

                    Frm_MachineConfig.Instance.ReloadProject();

                    Frm_Home.Instance.ReadHistoryData();
                    Machine.MachineResourceInit();
                }
            }
            else
            {
                MessageBox.Show(this, "无权限!", "Tip", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

        }

        private void tsmi_NewProject_Click(object sender, EventArgs e)
        {
            if (username == "Apple" || username == "superadmin"
                     || username == "EN"
                     || username == "Battery QM")
            {
                if (MachineStatusManager.CurrentMachineStatus == MachineStatus.Homing
                      || MachineStatusManager.CurrentMachineStatus == MachineStatus.Running
                      )
                {
                    MessageBox.Show("设备正在运行，请先停止！");
                }
                Dlg_SelectProject selectProjectDialog = new Dlg_SelectProject();
                selectProjectDialog.Title = "新建项目";
                if (selectProjectDialog.ShowDialog(Frm_Home.Instance) != DialogResult.OK)
                {
                    return;
                }

                MachineDataManager.ProjectName = ProjectName;
                ucBtnExt_MachineInfo.BtnText = ProjectName;

                MachineDataManager.Instance.Init();
                MachineDataManager.LoadFromFile();

                Frm_MachineConfig.Instance.ReloadProject();

                Frm_Home.Instance.ReadHistoryData();
                Machine.MachineResourceInit();
            }
            else
            {
                MessageBox.Show(this, "无权限!", "Tip", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
        }


        public class UserOptionCheckBFMessage : IMessageFilter
        {
            public bool RegiserLockFlag = true;
            public int nUserOptionsCount = 0;

            public bool PreFilterMessage(ref Message m)
            {
                //检测鼠标或者键盘的消息
                if (m.Msg == 0x0200 || m.Msg == 0x0201 || m.Msg == 0x0204 || m.Msg == 0x0207)
                {
                    nUserOptionsCount = 0;
                }
                return false;
            }
        }

        public void UpdateStartOnce(bool? 启动一次, string msg = "")
        {
            if (Common.启动一次 == false)
            {
                btn_StartOnce.BackColor = Color.Gray;
            }
            else if (Common.启动一次 == true)
            {
                btn_StartOnce.BackColor = Color.Green;
            }
            else
            {
                btn_StartOnce.BackColor = Color.Transparent;
            }

            if (!string.IsNullOrEmpty(msg))
            {
                btn_StartOnce.Text = "启动一次" + msg;
            }
            else
            {
                btn_StartOnce.Text = "启动一次";
            }
        }
        private void btn_StartOnce_Click(object sender, EventArgs e)
        {
            if (启动一次 == false)
            {
                启动一次 = true;
                UpdateStartOnce(启动一次);
            }
            else
            {
                启动一次 = false;
                UpdateStartOnce(启动一次);
            }
        }
        private void btn_DT_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定[是否进入维护模式]", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                Dlg_ManualDownBegin.Instance.alarmInfo = new AlarmInfo() { StartTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")) };
                Dlg_ManualDownBegin.Instance.Show();
            }
            else
            {

            }
        }

        private void ProTypeListItemsInit()
        {
            tscb_ProTypeList.Items.Clear();
            foreach (var item in ProductTypeMeasureItemEnableList)
            {
                tscb_ProTypeList.Items.Add(item.ProductType);
            }
            tscb_ProTypeList.SelectedItem = CurProType;

            CurProTypeMeasureItems = ProductTypeMeasureItemEnableList.Find(x => x.ProductType.Equals(CurProType));
            if (CurProTypeMeasureItems == null)
            {
                AppendUiLog.Log($"选择当前产品类型异常", LogType.Error);
            }
        }
        private void tscb_ProTypeList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (MachineStatusManager.CurrentMachineStatus == MachineStatus.Initialized
                || MachineStatusManager.CurrentMachineStatus == MachineStatus.Ready
                || MachineStatusManager.CurrentMachineStatus == MachineStatus.Pause)
            {
                if (tscb_ProTypeList.SelectedItem.ToString() != CurProType)
                {
                    CurProType = tscb_ProTypeList.SelectedItem.ToString();
                    if (CurProType == "Block_Min")
                        whichBlock = 0;
                    else if (CurProType == "Block_Mid")
                        whichBlock = 1;
                    else if (CurProType == "Block_Max")
                        whichBlock = 2;
                    else
                        whichBlock = -1;
                    Frm_Setting.Instance.DgvBindSource();
                    Frm_Home.Instance.tb_ext.Text = $"{CurProType}_{Common.startDate}";
                    CurProTypeMeasureItems = ProductTypeMeasureItemEnableList.Find(x => x.ProductType.Equals(CurProType));
                    if (CurProTypeMeasureItems == null)
                        AppendUiLog.Log($"选择当前产品类型异常", LogType.Error);
               
                    Frm_Home.Instance.RefreshHomeUI(CurProType);
                    Frm_Home.Instance.ReadHistoryData();
                    Frm_Setting.Instance.DgvBindSource();
                    PublicMethod.WriteCurProTypeIni(CurProType);
                    Machine.ImageLightInit();
                    Measure1.Instance.SetLaserParam();
                    PublicMethod.ReadCSVFile();
                    PublicMethod.Stop();
                }
            }
            else
            {
                if (CurProType != tscb_ProTypeList.SelectedItem.ToString())
                {
                    MessageBox.Show("禁止切换产品", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    tscb_ProTypeList.Text = CurProType;
                }
            }
        }


        private void UpdateProTypeMeasureItemsEnable(List<ProductTypeMeasureItemEnable> productTypeMeasureItemEnables)
        {
            if (ProductTypeMeasureItemEnableList.Count > 0)
            {
                bool isContainCurProType = false;
                foreach (var item in ProductTypeMeasureItemEnableList)
                {
                    if (item.ProductType.Equals(CurProType))
                        isContainCurProType |= true;
                }
                if (isContainCurProType)
                {
                    ProTypeListItemsInit();
                }
                else
                {
                    tscb_ProTypeList.Items.Clear();
                    foreach (var item in ProductTypeMeasureItemEnableList)
                    {
                        tscb_ProTypeList.Items.Add(item.ProductType);
                    }
                    tscb_ProTypeList.SelectedIndex = 0;
                    CurProType = tscb_ProTypeList.SelectedItem.ToString();

                    CurProTypeMeasureItems = ProductTypeMeasureItemEnableList.Find(x => x.ProductType.Equals(CurProType));
                    if (CurProTypeMeasureItems == null)
                    {
                        AppendUiLog.Log($"选择当前产品类型异常", LogType.Error);
                    }
                }
            }
            else
            {
                //todo
            }
        }

        private void btn_Sample_Click(object sender, EventArgs e)
        {
            Dlg_Sample sampleDialog = new Dlg_Sample();
            sampleDialog.ShowDialog(this);
        }

        private void ScreenMode_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ScreenMode.Text == "投屏1")
                PublicMethod.SetScreenMode(3);
            else
                PublicMethod.SetScreenMode(0);
        }

        private void btPointCheck_PLC_Click(object sender, EventArgs e)
        {

        }

        private void Btn_OpenDoor_Click(object sender, EventArgs e)
        {
            Common.OpenDoor = !Common.OpenDoor;
            if (Common.OpenDoor)
            {
                Btn_OpenDoor.BackColor = Color.Green;

            }
            else
            {
                Btn_OpenDoor.BackColor = Color.White;
            }

        }

        private void Btn_CloDoor_Click(object sender, EventArgs e)
        {
            Common.ClooseDoor = !Common.ClooseDoor;
            if (Common.ClooseDoor)
            {
                Btn_CloDoor.BackColor = Color.Green;

            }
            else
            {
                Btn_CloDoor.BackColor = Color.White;
            }
        }
    }
}